package com.cardmanager.pro.service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cardmanager.pro.authorization.CreditCardManagerAuthorizationHandle;
import com.cardmanager.pro.business.CreditCardAccountBusiness;
import com.cardmanager.pro.business.CreditCardAccountHistoryBusiness;
import com.cardmanager.pro.business.RepaymentTaskPOJOBusiness;
import com.cardmanager.pro.pojo.CreditCardAccount;
import com.cardmanager.pro.pojo.CreditCardAccountHistory;
import com.cardmanager.pro.pojo.RepaymentTaskPOJO;
import com.cardmanager.pro.scanner.RepaymentTaskScanner;
import com.cardmanager.pro.util.RestTemplateUtil;

import cn.jh.common.utils.CommonConstants;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class CreditCardAccountService {
	
	private final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	private RestTemplateUtil util;
	
	@Autowired
	private CreditCardAccountBusiness creditCardAccountBusiness;
	
	@Autowired
	private RepaymentTaskPOJOBusiness repaymentTaskPOJOBusiness;
	
	@Autowired
	private CreditCardAccountHistoryBusiness creditCardAccountHistoryBusiness;
	
	@Autowired
	private CreditCardManagerAuthorizationHandle creditCardManagerAuthorizationHandle;
	
	@Autowired
	private RepaymentTaskScanner repaymentTaskScanner;
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/set/creditcardaccount")
	public @ResponseBody Object setCreditCardAccount(HttpServletRequest request,
			@RequestParam("userId")String userId,
			@RequestParam("creditCardNumber")String creditCardNumber,
			@RequestParam(value="creditBlance",required=false,defaultValue="")String creditBlanceStr,
			@RequestParam(value="billDate",required=false,defaultValue="")String billDateStr,
			@RequestParam(value="repaymentDate",required=false,defaultValue="")String repaymentDateStr,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object>map = new HashMap<>();
		userId = userId.trim();
		creditCardNumber = creditCardNumber.trim();
		creditBlanceStr = creditBlanceStr.trim();
		billDateStr = billDateStr.trim();
		repaymentDateStr = repaymentDateStr.trim();
		
		BigDecimal creditBlance = null;
		int billDate = 0;
		int repaymentDate = 0;
		Map<String, Object> creditCardAccountMap = creditCardManagerAuthorizationHandle.verifyIsRegister(userId, creditCardNumber,version);
		if(!CommonConstants.SUCCESS.equals(creditCardAccountMap.get(CommonConstants.RESP_CODE))){
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "修改成功");
			return map;
		}
		
		if(creditBlanceStr!=null&&!"".equals(creditBlanceStr)){
			Map<String, Object> verifyMoneyMap = creditCardManagerAuthorizationHandle.verifyMoney(creditBlanceStr,2,BigDecimal.ROUND_HALF_UP);
			if(!CommonConstants.SUCCESS.equals(verifyMoneyMap.get(CommonConstants.RESP_CODE))){
				return verifyMoneyMap;
			}
			creditBlance = (BigDecimal) verifyMoneyMap.get(CommonConstants.RESULT);
		}
		
		if(billDateStr!=null&&!"".equals(billDateStr)){
			try {
				billDate = Integer.valueOf(billDateStr);
			} catch (NumberFormatException e) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "输入日期格式非法,请重新输入");
				return map;
			}
			if(!(billDate >0 && billDate<32)){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "输入日期格式非法,请重新输入");
				return map;
			}
		}
		
		if(repaymentDateStr!=null&&!"".equals(repaymentDateStr)){
			try {
				repaymentDate = Integer.valueOf(repaymentDateStr);
			} catch (Exception e) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "输入日期格式非法,请重新输入");
				return map;
			}
			if(!(repaymentDate >0 && repaymentDate<32)){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "输入日期格式非法,请重新输入");
				return map;
			}
		}
		
		CreditCardAccount creditCardAccount = (CreditCardAccount) creditCardAccountMap.get(CommonConstants.RESULT);
		creditCardAccount.setCreditBlance(creditBlance!=null?creditBlance:creditCardAccount.getCreditBlance());
		creditCardAccount.setBillDate(0 != billDate?billDate:creditCardAccount.getBillDate());
		creditCardAccount.setRepaymentDate(0 != repaymentDate?repaymentDate:creditCardAccount.getRepaymentDate());
		
		creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
		
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "设置成功");
		map.put(CommonConstants.RESULT, creditCardAccount);
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/get/creditcardaccount")
	public @ResponseBody Object getCreditCardAccountByUserIdAndCreditCardNumber(HttpServletRequest request,
			@RequestParam("userId")String userId,
			@RequestParam("creditCardNumber")String creditCardNumber,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object>map = new HashMap<>();
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userId, creditCardNumber,version);
		
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, creditCardAccount);
		return map;
		
		
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/set/freezeblance/by/ordercode")
	public @ResponseBody Object setFreezeBlanceByOrderCode(HttpServletRequest request,
			@RequestParam(value="orderCode")String orderCode,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object> map = new HashMap<>();
		RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByOrderCode(orderCode);
		if(repaymentTaskPOJO!=null&& repaymentTaskPOJO.getOrderStatus() != 1 && repaymentTaskPOJO.getTaskStatus() != 2){
			repaymentTaskPOJO.setOrderStatus(0);
			repaymentTaskPOJO.setTaskStatus(2);
			List<CreditCardAccountHistory> creditCardAccountHistory = creditCardAccountHistoryBusiness.findByTaskId(repaymentTaskPOJO.getRepaymentTaskId());
			creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(), 3,creditCardAccountHistory.get(0).getAmount(),"任务执行失败,增加余额",version);
			repaymentTaskPOJO.setRealAmount(BigDecimal.ZERO);
			repaymentTaskPOJO.setDescription("还款失败!");
			repaymentTaskPOJO.setReturnMessage("还款失败,原因未知,等待系统自动出款!");
			repaymentTaskPOJO = repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "修改成功!");
		map.put(CommonConstants.RESULT, repaymentTaskPOJO);
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/open/withdraw/account")
	public @ResponseBody Object openWithdrawAccount(HttpServletRequest request,
			@RequestParam(value="creditCardNumber")String creditCardNumber,
			@RequestParam(value="phone")String phone,
			@RequestParam(value="brandId")String brandId,
			@RequestParam(value="amount")String amountStr,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Map<String,Object> map = new HashMap<>();
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByCreditCardNumberAndVersion(creditCardNumber,version);
		if(creditCardAccount == null){
			LinkedMultiValueMap<String, String>requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("phone", phone);
			requestEntity.add("brandid", brandId);
			Map<String, Object> restTemplateDoPost = util.restTemplateDoPost("user", "/1.0/user/query/phonebrand", requestEntity);
			JSONObject resultJSONObject = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
			
			String userId = resultJSONObject.getString("id");
			
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("type", "0");
			requestEntity.add("cardNo", creditCardNumber);
			restTemplateDoPost = util.restTemplateDoPost("user", "/v1.0/user/bank/default/cardno", requestEntity);
			resultJSONObject = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
			if(resultJSONObject == null || !resultJSONObject.containsKey("id")){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "无该充值卡");
				return map;
			}
			
			Date nowTime = new Date();
			creditCardAccount = new CreditCardAccount();
			creditCardAccount.setUserId(userId);
			creditCardAccount.setCreditCardNumber(creditCardNumber);
			creditCardAccount.setPhone(phone);
			creditCardAccount.setLastUpdateTime(nowTime);
			creditCardAccount.setCreateTime(nowTime);
		}
		BigDecimal amount = new BigDecimal(amountStr);
		if(BigDecimal.ZERO.compareTo(amount) >= 0){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "提现金额有误!");
			return map;
		}
		creditCardAccount.setBlance(creditCardAccount.getBlance().add(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
		creditCardAccount = creditCardAccountBusiness.save(creditCardAccount);
		map = (Map<String, Object>) repaymentTaskScanner.clearAccountByUserIdAndCreditCardNumber(request, creditCardAccount.getUserId(), creditCardNumber,null,"0",version);
		return map;
	}
	
}
